﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WFNetLib.Net;

namespace PortmonAnalyse
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripComboBox1.Items.Clear();
            EncodingInfo[] es = Encoding.GetEncodings();
            int index=-1;
            foreach (EncodingInfo ei in es)
            {
                int x=toolStripComboBox1.Items.Add(ei.Name);
                if(index==-1)
                {
                    if(ei.Name=="utf-8")
                        index = x;
                }
            }
            toolStripComboBox1.SelectedIndex=index;
        }
        string[] strP;
        List<byte> dList = new List<byte>();
        ListViewItem li = null;
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                listView1.Items.Clear();
                FileInfo f = new FileInfo(openFileDialog1.FileName);                
                this.Text = "串口数据分析" + "----" + f.Name;
                FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
                StreamReader sw = new StreamReader(fs);                
                bool b7E=false;
                bool bIP = false;
                
                while (sw.Peek() >= 0)
                {
                    string str1;
                    string str2; 
                    string strLine = sw.ReadLine();
                    Application.DoEvents();
                    string[] strArr = strLine.Split(':');
                    if (strArr.Length != 2)
                    {
                        if (strArr.Length != 4)
                        {
                            textBox1.AppendText(strLine + "\r\n");
                            continue;
                        }
                        else
                        {
                            str1 = strLine.Substring(0, strLine.LastIndexOf(':'));
                            str2 = strLine.Substring(strLine.LastIndexOf(':') + 1);
                        }
                    }
                    else
                    {
                        str1 = strArr[0];
                        str2 = strArr[1];
                    }
                        strP = str1.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                        try
                        {
                            byte[] bs = WFNetLib.Strings.StringsFunction.strToHexByte(str2.Split('\t')[0], " ");
                            List<byte> bsList = new List<byte>(bs);
                            if(b7E)//已经开始了数据传输，但是没有收到尾
                            {
                                while (true)
                                {
                                    if (bsList.Count == 0)
                                        break;
                                    if(b7E)
                                    {
                                        if (bIP)
                                        {
                                            for (int i = 0; i < bsList.Count; i++)
                                            {
                                                if (bsList[i] != 0x7e)
                                                    dList.Add(bsList[i]);
                                                else
                                                {
                                                    b7E = false;
                                                    bIP = false;
                                                    dList.Insert(0, 0x7e);
                                                    dList.Add(0x7e);
                                                    Add(2);
                                                    dList.Clear();
                                                    bsList.RemoveRange(0, i+1);
                                                    break;
                                                }
                                            }
                                            if(b7E)
                                                break;
                                        }
                                        else
                                        {
                                            for (int i = 0; i < bsList.Count; i++)
                                            {
                                                if (bsList[i] != 0x7e)
                                                    dList.Add(bsList[i]);
                                                else
                                                {
                                                    b7E = false;
                                                    dList.Insert(0, 0x7e);
                                                    dList.Add(0x7e);
                                                    Add(1);
                                                    dList.Clear();
                                                    bsList.RemoveRange(0, i+1);
                                                    break;
                                                }
                                            }
                                            if (b7E)
                                                break;
                                        }
                                    }
                                    else
                                    {
                                        if (bsList[0] == 0x7e)
                                        {
                                            bsList.RemoveAt(0);
                                            b7E = true;
                                        }
                                        if (bsList[0] == 0x21)//ip协议
                                        {
                                            b7E = true;
                                            bIP = true;
                                            for (int i = 0; i < bsList.Count; i++)
                                            {
                                                if (bsList[i] != 0x7e)
                                                    dList.Add(bsList[i]);
                                                else
                                                {
                                                    b7E = false;
                                                    bIP = false;
                                                    dList.Insert(0, 0x7e);
                                                    dList.Add(0x7e);
                                                    Add(2);
                                                    dList.Clear();
                                                    bsList.RemoveRange(0, i+1);
                                                    break;
                                                }
                                            }
                                            if (b7E)
                                                break;
                                        }
                                        else
                                        {
                                            if ((bsList[0] == 0xff) ||
                                                (bsList[0] == 0xc0 && bsList[1] == 0x21) ||
                                                (bsList[0] == 0xc0 && bsList[1] == 0x23) ||
                                                (bsList[0] == 0x80 && bsList[1] == 0x21))
                                            {
                                                b7E = true;
                                                for (int i = 0; i < bsList.Count; i++)
                                                {
                                                    if (bsList[i] != 0x7e)
                                                        dList.Add(bsList[i]);
                                                    else
                                                    {
                                                        b7E = false;
                                                        dList.Insert(0, 0x7e);
                                                        dList.Add(0x7e);
                                                        Add(1);
                                                        dList.Clear();
                                                        bsList.RemoveRange(0, i+1);
                                                        break;
                                                    }
                                                }
                                                if (b7E)
                                                    break;
                                            }
                                            else
                                            {
                                                for (int i = 0; i < bsList.Count; i++)
                                                {
                                                    dList.Add(bsList[i]);
                                                }
                                                Add(0);
                                                dList.Clear();
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                while(true)
                                {
                                    if(bsList.Count==0)
                                        break;
                                    if (bsList[0] == 0x7e)
                                    {
                                        bsList.RemoveAt(0);
                                        b7E = true;
                                    }
                                    if (bsList[0] == 0x21)//ip协议
                                    {
                                        b7E = true;
                                        bIP = true;
                                        for (int i = 0; i < bsList.Count; i++)
                                        {
                                            if (bsList[i] != 0x7e)
                                                dList.Add(bsList[i]);
                                            else
                                            {
                                                b7E = false;
                                                bIP = false;
                                                dList.Insert(0, 0x7e);
                                                dList.Add(0x7e);
                                                Add(2);
                                                dList.Clear();
                                                bsList.RemoveRange(0, i+1);
                                                break;
                                            }
                                        }
                                        if (b7E)
                                            break;
                                    }
                                    else
                                    {
                                        if ((bsList[0] == 0xff) ||
                                            (bsList[0] == 0xc0 && bsList[1] == 0x21) ||
                                            (bsList[0] == 0xc0 && bsList[1] == 0x23) ||
                                            (bsList[0] == 0x80 && bsList[1] == 0x21))
                                        {
                                            b7E = true;
                                            for (int i = 0; i < bsList.Count; i++)
                                            {
                                                if (bsList[i] != 0x7e)
                                                    dList.Add(bsList[i]);
                                                else
                                                {
                                                    b7E = false;
                                                    dList.Insert(0, 0x7e);
                                                    dList.Add(0x7e);
                                                    Add(1);
                                                    dList.Clear();
                                                    bsList.RemoveRange(0, i+1);
                                                    break;
                                                }
                                            }
                                            if (b7E)
                                                break;
                                        }
                                        else
                                        {
                                            for (int i = 0; i < bsList.Count; i++)
                                            {
                                                dList.Add(bsList[i]);
                                            }
                                            Add(0);
                                            dList.Clear();
                                            break;
                                        }
                                    }
                                }
                            }
                            
                        }
                         catch (System.Exception ex)
                         {
                             textBox1.AppendText(ex.Message + "\r\n");
                             textBox1.AppendText(strLine + "\r\n");
                         }
                    }
                
                sw.Close();
                fs.Close();
            }
        }
        void Add(int type)
        {
            li = listView1.Items.Add(strP[0]);//编号
            if (strP[3] == "IRP_MJ_WRITE")
            {
                li.SubItems.Add("发送");
            }
            else if (strP[3] == "IRP_MJ_READ")
            {
                li.SubItems.Add("接收");
                li.BackColor = Color.BurlyWood;
            }
            string str="";
            List<byte> s = new List<byte>();
            switch (type)
            {
                case 0://at
                    li.SubItems.Add("at");
                    li.SubItems.Add((dList.Count).ToString());
                    li.SubItems.Add(WFNetLib.Strings.StringsFunction.byteToHexStr(dList.ToArray(), " "));
                    str = Encoding.GetEncoding(toolStripComboBox1.Text).GetString(dList.ToArray());
                    str = str.Replace("\r", "\\r");
                    str = str.Replace("\n", "\\n");
                    li.SubItems.Add(str);
                    break;
                case 1://ppp                    
                    li.SubItems.Add("ppp");
                    li.SubItems.Add((dList.Count + 2).ToString());
                    s = WFNetLib.Net.pppDataTransferConvert.PPPDataDecode(dList);
                    li.SubItems.Add(WFNetLib.Strings.StringsFunction.byteToHexStr(s.ToArray(), " "));                                                   
                    break;
                case 2://IP
                    li.SubItems.Add("IP");
                    li.SubItems.Add((dList.Count).ToString());
                    s = WFNetLib.Net.pppDataTransferConvert.PPPDataDecode(dList);
                    str=WFNetLib.Strings.StringsFunction.byteToHexStr(s.ToArray()," ");
                    li.SubItems.Add(str);

                    int index = WFNetLib.BytesOP.GetLowNibble(s[2]) * 4;
                    index += WFNetLib.BytesOP.GetHighNibble(s[2 + index + 12]) * 4;
                    index += 2;
                    
                    List<byte> ipList = new List<byte>();
                    for (int j = index; j < s.Count - 3; j++)
                    {
                        ipList.Add(s[j]);
                    }
                    str = " ";
                    if (ipList.Count != 0)
                    {
                        str = Encoding.GetEncoding(toolStripComboBox1.Text).GetString(ipList.ToArray());
                        str = str.Replace("\r", "\\r");
                        str = str.Replace("\n", "\\n");                        
                    }
                    li.SubItems.Add(str);
                    IPPacket ipUp;
                    try
                    {
                        ipUp = IPPacket.MakeIPPacket(s, 2);
                        StringBuilder sb = new StringBuilder();
                        sb.Append("版本:" + ipUp.Version.ToString()+"\\r\\n");
                        sb.Append("首部长度:" + (ipUp.HeaderLength*4).ToString() + "\\r\\n");
                        sb.Append("服务类型:"+ipUp.TypeOfService.ToString()+"\\r\\n");
                        sb.Append("数据包长度:"+ipUp.TotalLength.ToString()+"\\r\\n");
                        sb.Append("标识符:"+ipUp.Identification.ToString()+"\\r\\n");
                        sb.Append("标志:"+ipUp.Flags.ToString()+"\\r\\n");
                        sb.Append("段偏移:"+ipUp.FragmentOffset.ToString()+"\\r\\n");
                        sb.Append("生存时间:"+ipUp.TimeToLive.ToString()+"\\r\\n");
                        sb.Append("协议:"+ipUp.Protocol.ToString()+"\\r\\n");
                        sb.AppendFormat("源IP:{0}.{1}.{2}.{3}\\r\\n", ipUp.SourceAddress[0].ToString(), ipUp.SourceAddress[1].ToString(), ipUp.SourceAddress[2].ToString(), ipUp.SourceAddress[3].ToString());
                        sb.AppendFormat("目标IP:{0}.{1}.{2}.{3}\\r\\n", ipUp.DastinationAddress[0].ToString(), ipUp.DastinationAddress[1].ToString(), ipUp.DastinationAddress[2].ToString(), ipUp.DastinationAddress[3].ToString());
                        
                        sb.Append("IP选项:");
                        try
                        {
                            for (int i = 0; i < ipUp.Options.Count; i++)
                            {
                                sb.Append(ipUp.Options[i].ToString("X2") + " ");
                            }
                        }
                        catch { }
                        sb.Append("\\r\\n");                        
                        TCPPacket tcpUp = (TCPPacket)ipUp.oProtocolContent;
                        sb.Append("-----------------------------------------------------------------"+"\\r\\n");
                        sb.Append("源端口:"+tcpUp.SourcePort.ToString()+"\\r\\n");
                        sb.Append("目标端口:"+tcpUp.DastinationPort.ToString()+"\\r\\n");
                        sb.Append("编号:"+tcpUp.InitialSeqNumber.ToString()+"\\r\\n");
                        sb.Append("回应编号:"+tcpUp.AckSeqNumber.ToString()+"\\r\\n");
                        sb.Append("数据偏移:"+tcpUp.DataOffset.ToString()+"\\r\\n");
                        sb.Append("TCP标志:"+tcpUp.TCPFlags.ToString("X2")+"\\r\\n");
                        sb.Append("窗口:"+tcpUp.Window.ToString()+"\\r\\n");
                        sb.Append("紧急指针:"+tcpUp.UrgentPoint.ToString()+"\\r\\n");
                        sb.Append("TCP选项:");
                        try
                        {
                            for (int i = 0; i < tcpUp.TCPOptions.Count; i++)
                            {
                                sb.Append(tcpUp.TCPOptions[i].ToString("X2") + " ");
                            }
                        }
                        catch { }
                        sb.Append("\\r\\n");
                        li.SubItems.Add(sb.ToString());
                    }
                    catch { }
                    
                    break;
            }

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count != 0)
            {
                Form2 f = new Form2(listView1.SelectedItems[0]);
                f.Show(this);
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
                return;
//             ListViewItem li;
//             li = listView1.SelectedItems[0];
//             if (li != null)
//             {
//                 try
//                 {
//                     string str = li.SubItems[5].Text;
//                     str = str.Replace("\\r", "\r");
//                     str = str.Replace("\\n", "\n");
//                     toolTip1.SetToolTip(listView1, str);
//                 }
//                 catch
//                 {
//                     toolTip1.Hide(listView1);
//                 }                
//             }
        }
    }
}
